<?php
class MemberController extends Zend_Controller_Action
{
	protected $db; // 数据库指针

	// 初始化
	function init()
	{
		// 取得数据库指针
		$this->db=Zend_Registry::get('database');
		$this->view->action=$this->_getParam('action');
		$this->view->controller=$this->_getParam('controller');

		// 默认载入的js
		$this->view->javascript=array('jquery.inline.js', 'paper.js');

		// 取得登录状态
		$login=Zend_Registry::get('login');
		if (is_array($login)) {
			$this->view->aid=$login['AId'];
			$this->view->priv=$login['Priv'];
			$this->view->name=$login['Name'];
		}
		else {
			$this->view->aid=$this->view->priv=$this->view->name=0;
		}

		// 默认标题
		$this->view->title='吉林大学软件教研室';
	}

	// 处理no action异常
	function __call($method, $args)
	{
		if ('Action'==substr($method, -6)) {
			$this->view->action=substr($method, 0, -6);
			$this->view->param=$this->_getAllParams();
			$this->renderScript('error/no-action.php');
		}
		else // 其他异常
			$this->_redirect('/');
	}

	/* 下面是action处理函数: ***************************/

	// 成员首页
	function indexAction()
	{
		$this->view->title='全部成员－软件教研室';

		$db = new AccountDb();

		$this->view->teacher = $db->Teacher(); 
		$this->view->phd = $db->Phd();
		$this->view->master = $db->Master();
		$this->view->graduate = $db->Graduate();
	}

	// 登录
	function loginAction()
	{
		$url=$this->_getParam('url');
		$user=$this->_getParam('User');
		$pass=md5($this->_getParam('Pass'));
		$acc=member::login($this->db, $user, $pass); // acc is account
		if (is_array($acc)) {
			$_SESSION['AId']=$acc['AId'];
			$_SESSION['Priv']=$acc['Priv'];
			$_SESSION['Name']=$acc['Name'];
			$_SESSION['User']=$acc['User'];
		}
		$this->_redirect($url);
	}

	// 登出
	function logoutAction()
	{
		$_SESSION=array();
		if (isset($_COOKIE[session_name()]))
			setcookie(session_name(), '', time()-57, '/');
		session_destroy();
		$this->_redirect('/');
	}

	// 显示详细信息
	function infoAction()
	{
		// 判断是否可以编辑该人信息
		$this->view->aid = $aid = intval($this->_getParam('AId'));
		$this->view->edit = auth::aid()==$aid ||
							auth::check(auth::PRIV_ADMIN);
		
		// 查询信息
		$db = new AccountDb();
		$data = $db->Fetch($aid);
		$this->view->status = $data[0]['Status'];
		$data = $db->Format($data);
		$this->view->data = $data[0];
		$paper=new paper();
		$this->view->paper = $paper->find($aid, '`Date` desc', 500);
		$this->view->title=$this->view->data['Name'].'－软件教研室';

	}

	// 修改个人信息
	function editAction()
	{
		// 判断是否可以编辑该人信息
		$this->view->aid = $aid = intval($this->_getParam('AId'));
		$this->view->edit = $aid==$aid || auth::check(auth::PRIV_ADMIN);
		
		// 查询信息
		$db = new AccountDb();
		$data = $db->Fetch($aid);
		$this->view->status = $data[0]['Status'];
		$this->view->info = $data[0];
		$data = $db->Format($data);
		$this->view->data = $data[0];
		$this->view->data['Birth'] = strftime('%Y-%m-%d', 
										$this->view->info['Birth']);
		$this->view->data['EnrollDate'] = strftime('%Y',
										$this->view->info['EnrollDate']);

		$this->view->title = '修改个人信息－软件教研室';
	}

	// 显示增加成员窗口
	function addpersonAction()
	{
		$this->view->status=$this->_getParam('Status');
	}

	// 增加成员
	function addAction()
	{
		$status=$this->_getParam('Status');
		switch ($status) {
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
			$priv=auth::PRIV_ADMIN;
			$this->_setParam('Priv', auth::PRIV_TEACHER);
			$this->_setParam('Title', '教师');
			break;
		case 2:
			$priv=auth::PRIV_TEACHER;
			$this->_setParam('Priv', auth::PRIV_STUDENT);
			$this->_setParam('Title', '在读博士');
			break;
		case 1:
			$priv=auth::PRIV_TEACHER;
			$this->_setParam('Priv', auth::PRIV_STUDENT);
			$this->_setParam('Title', '在读研究生');
			break;
		case 0:
			$priv=auth::PRIV_TEACHER;
			$this->_setParam('Priv', auth::PRIV_STUDENT);
			$this->_setParam('Title', '毕业生');
			break;
		}

		// 权限判断
		if (!auth::check($priv)) {
			$this->view->msg='你的权限不够。';
			$this->renderScript('error/small-msg.php');
			return;
		}

		$user=$this->_getParam('User');
		$pass=$this->_getParam('Pass');
		$this->_setParam('Pass', md5($pass));

		$table=new account();
		$param=$this->_getAllParams();
		$param['EnrollDate']=strtotime($param['EnrollDate']);
		$result=$table->check($param);
		if ($result==-1) {
			$this->view->msg='缺少参数 "'.$table->err_field().'" 。';
		}
		else if ($result==-2) {
			$this->view->msg='参数 "'.$table->err_field().'" 不正确。';
		}
		else {
			try {
				$result=$table->insert($param);
				$this->view->msg='新成员创建成功。';
				$this->view->more="登录名: $user &nbsp;|&nbsp; 密码: ".
							"$pass &nbsp;|&nbsp; 序号: $result";
			}
			catch (Zend_Exception $e) {
				$this->view->msg='新成员创建失败，可能因为登录名重复！';
			}
		}
	
		$this->renderScript('error/small-msg.php');
	}

	// 个人论文管理
	function paperAction()
	{
		// 权限判断
		$aid=$this->_getParam('AId');
		if (auth::aid()!=$aid) {
			$this->view->msg='权限错误。';
			$this->renderScript('error/small-msg.php');
			return;
		}

		// 所有成员
		/*
		$db = new AccountDb();
		$this->view->teacher = $db->Teacher(); 
		$this->view->phd = $db->Phd();
		$this->view->master = $db->Master();
		$this->view->graduate = $db->Graduate();
		*/

		// 查询出本人的所有论文
		$this->view->edit_paper=true;
		$paper=new paper();
		$this->view->paper=$paper->find(auth::aid(), '`Date` desc',	500);
	}

	// 检测论文名
	function checkTitleAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$title=$this->_getParam('Title');
		if (strlen($title)<4) {
			echo '<font color="#ff0000">　FAILED. 标题太短。</font>';
			return;
		}
		$paper=new paper();
		echo $paper->check_title($title)?
			"<font color='#006700'>　OK. 论文名验证通过。</font>":
			'<font color="#ff0000">　FAILED. 该论文已存在，'.
				'不能重复增加论文。</font>';
	}

	// 增加论文到数据库
	function addPaperAction()
	{
		// 权限判断
		if (!auth::aid()) {
			$this->view->msg='你还没有登录。';
			$this->renderScript('error/small-msg.php');
			return;
		}

		// 保存论文
		$paper=new paper();
		$param=$this->_getAllParams();
		$result=$paper->check($param);
		if ($result==-1) {
			$this->view->msg='缺少参数 "'.$paper->err_field().'" 。';
			$this->renderScript('error/small-msg.php');
			return;
		}
		else if ($result==-2) {
			$this->view->msg='参数 "'.$paper->err_field().'" 不正确。';
			$this->renderScript('error/small-msg.php');
			return;
		}
		else { // 参数验证成功，保存入数据库
			$this->_helper->viewRenderer->setNoRender();
			$pid=$paper->add($param);
			include_once 'member/paper-list.php';
			if ($pid>0) {
				$param['PId']=$pid;
				$param['Date']=strtotime($param['Date']);
				echo paper_format($param, true);
			}
			else
				echo '<p style="color:#f00;">FAILED. 保存失败。</p>';
		}
	}

	// 显示论文详细信息
	function paperDetailAction()
	{
		$pid=$this->_getParam('PId');

		// 所有成员
		$acc=new account();
		$this->view->teacher=array();
		$this->view->phd=array();
		$this->view->master=array();
		$this->view->graduate=array();
		$acc->all_member(&$this->view->teacher,
						&$this->view->phd,
						&$this->view->master,
						&$this->view->graduate);

		// 论文全文
		$paper=new paper();
		$this->view->data=$paper->detail($pid);
		
		// 权限判断
		if (preg_match('/\(id='.auth::aid().'\)/', 
					$this->view->data['Author']) || 
				auth::check(auth::EDIT_LAB_STUFF)) {
			$this->view->edit=true;
		}
	}

	// 删除一篇论文
	function delPaperAction()
	{
		$aid=auth::aid();
		$pid=$this->_getParam('PId');

		$paper=new paper();
		if ($paper->is_author($aid, $pid) || auth::check(auth::EDIT_LAB_STUFF)) {
			$result=$paper->del($pid);
			$this->view->msg=$result?'OK. 删除成功。':'FAILED. 删除失败。';
		}
		else { // 越权
			$this->view->msg='你的权限不够。';
		}

		$this->renderScript('error/msg.php');
	}

	// 修改论文信息
	function updatePaperAction()
	{
		$paper=new paper();
		$aid=auth::aid();
		$pid=$this->_getParam('PId');

		// 判断权限
		if (!$paper->is_author($aid, $pid) && 
				!auth::check(auth::EDIT_LAB_STUFF)) {
			$this->view->msg='你的权限不够。';
			$this->renderScript('error/msg.php');
			return;
		}

		// 更新论文内容
		$this->_helper->viewRenderer->setNoRender();
		echo $paper->update($this->_getAllParams(), $pid);
	}

	// 更新人的信息
	function updateAction()
	{
		$this->_helper->viewRenderer->setNoRender();

		// 判断是否可以编辑该人信息
		$param = $this->_getAllParams();
		$aid = intval($param['AId']);
		unset($param['AId']);
		if ($aid!=auth::aid() && !auth::check(auth::PRIV_ADMIN)) { // 越权
			$this->view->msg = "你的权限不够，请先登录。";
			$this->renderScript('error/small-msg.php');
			return;
		}

		// 检查信息有效性
		if (isset($param['Birth'])) {
			if (strlen($param['Birth'])<=4) 
				$param['Birth'] .= '-7-24';
			$param['Birth'] = strtotime($param['Birth']);
		}
		if (isset($param['EnrollDate'])) {
			if (strlen($param['EnrollDate'])<=4)
				$param['EnrollDate'] .= '-9-1';
			$param['EnrollDate'] = strtotime($param['EnrollDate']);
		}

		if (!auth::check(auth::PRIV_TEACHER))
			unset($param['Status']);
		else {
			switch ($param['Status']) {
			case 0:
			case 1:
			case 2:
				$param['Priv'] = auth::PRIV_STUDENT;
				break;
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				$param['Priv'] = auth::PRIV_TEACHER;
				break;
			} // end of switch
		}

		$db = new AccountDb;
		$tmp = $db->Fetch($aid);
		if ($tmp[0]['Priv']==auth::PRIV_ADMIN)
			$param['Priv'] = auth::PRIV_ADMIN;
		$result = $db->Check($param);
		if (!is_array($result)) { // check failed
			$this->view->msg = $db->Error();
			$this->renderScript('error/small-msg.php');
			//echo json_encode(array('type'=>-3, 'field'=>$db->->Field(),
			//						'data'=>$acc->Error() )
			//				);
			return;
		}

		// 更新信息
		$result = $db->Update($aid, $param);
		if ($result!=1) { // update error
			$this->view->msg = "Oops! 更新失败，请稍后再试。";
			$this->renderScript('error/small-msg.php');
			return;
		}

		$this->view->msg = "操作成功。";
		$this->renderScript('error/small-msg.php');
	}

	// 上传新头像对话框
	function iconAction()
	{
		$this->view->aid=$this->_getParam('AId');
	}

	// 处理上传头像
	function uploadiconAction()
	{
		$aid = $this->_getParam('AId');
		if (auth::aid()!=$aid && !auth::check(auth::PRIV_ADMIN)) {
			$this->view->msg = "你的权限不够，请先登录。";
			$this->renderScript('error/small-msg.php');
			return;
		}
		$this->view->url = upload::icon('file', $aid, $this->db);
	}

	// 修改密码对话框
	function passwordAction()
	{
		$this->view->aid = auth::aid();
	}

	// 修改密码
	function changepassAction()
	{
		$pass0 = $this->_getParam('Pass0'); // old
		$pass = $this->_getParam('Pass'); // new
		$pass1 = $this->_getParam('Pass2'); // re
		if ($pass!=$pass1) {
			$this->view->msg = 'Oops! 两次输入的密码不一致。';
			return;
		}
		else if (strlen($pass)<6) {
			$this->view->msg = 'Oops! 密码长度不能小于6。';
			return;
		}

		$pass = md5($pass1);
		$pass0 = md5($pass0);
		$aid = auth::aid();
		$table = new account;
		$result = $table->change_pass($aid, $pass0, $pass);
		if ($result==0)
			$this->view->msg = 'Oops! 原密码不正确。';
		else
			$this->view->msg = 'OK.';
	}

	// 编辑教师个人空间
	function teacherAction()
	{
		if (!auth::check(auth::PRIV_TEACHER)) {
			$this->view->msg = "你的权限不够，请先登录。";
			$this->renderScript('error/small-msg.php');
			return;
		}

		$this->view->title = '个人空间－软件教研室';
		$this->view->msg = $this->_getParam('msg');
		html::InitDir(auth::user());
		$this->view->files = html::Load('teacher', false, 
										'/pub/teacher/'.auth::user());
	}

	// 上传教师个人页面
	function uploadAction()
	{
		if (!auth::check(auth::PRIV_TEACHER)) {
			$this->view->msg = "你的权限不够，请先登录。";
			$this->renderScript('error/small-msg.php');
			return;
		}

		$result = upload::teacher(auth::user(), 'file');
		if ($result==1)
			$msg = 'File uploaded!';
		else
			$msg = 'Upload failed. Please try it later.';
		$this->_redirect('/member/teacher/?msg='.$msg);

	}

	// 删除教师静态页面
	function delAction()
	{
		if (!auth::check(auth::PRIV_TEACHER)) {
			$this->view->msg = "你的权限不够，请先登录。";
			$this->renderScript('error/small-msg.php');
			return;
		}

		$file = $this->_getParam('file');
		$result = html::DelTeacher(auth::user(), $file);
		if ($result)
			echo '1';
		else
			echo '0';
		$this->_helper->viewRenderer->setNoRender();
	}


};
?>
